package com.example.statistics.ex

import java.math.BigDecimal

/**
 * 加法
 */
fun Number?.addEx(num: Number?, scale: Int = 2): BigDecimal {
    val a = BigDecimal((this ?: 0).toString())
    val b = BigDecimal((num ?: 0).toString())
    return a.add(b).setDecimalPoint(scale)
}

/**
 * 累加求和
 */
inline fun <T> Iterable<T>.sumEx(selector: (T) -> Number): BigDecimal {
    var sum = BigDecimal(0)
    for (element in this) {
        sum = sum.addEx(selector(element))
    }
    return sum
}

/**
 * 减法
 */
fun Number?.subEx(num: Number?, scale: Int = 2): BigDecimal {
    val a = BigDecimal((this ?: 0).toString())
    val b = BigDecimal((num ?: 0).toString())
    return a.subtract(b).setDecimalPoint(scale)
}

/**
 * 乘法
 */
fun Number?.mulEx(num: Number?, scale: Int = 2): BigDecimal {
    val a = BigDecimal((this ?: 0).toString())
    val b = BigDecimal((num ?: 0).toString())
    val c = a.multiply(b).setDecimalPoint(scale)
    return c
}

/**
 * 除法
 */
fun Number?.divEx(num: Number?, scale: Int = 2): BigDecimal {
    val a = BigDecimal((this ?: 0).toString())
    val b = BigDecimal((num ?: 0).toString())
    return a.divide(b, scale, BigDecimal.ROUND_HALF_UP)
}

/**
 * 保留小数点位数
 */
fun BigDecimal.setDecimalPoint(scale: Int = 2): BigDecimal {
    return this.setScale(scale, BigDecimal.ROUND_HALF_UP)
}

/**
 * 求和是否相等
 */
fun Number?.isEqual(vararg number: Number): Boolean {
    var summation = BigDecimal(0)
    number.forEach {
        summation = summation.addEx(it)
    }
    return this == summation
}

fun Number?.display(): String {
    if (this == null) {
        return "0"
    }
    return this.toString().numberFormat
}


fun Int?.orEmpty(): Int {
    if (this == null)
        return 0
    return this
}

fun Float?.orEmpty(): Float {
    if (this == null)
        return 0f
    return this
}

fun Double?.orEmpty(): Double {
    if (this == null)
        return 0.0
    return this
}

fun Number?.setDecimalPoint(scale: Int = 2): BigDecimal {
    val a = BigDecimal((this ?: 0).toString())
    return a.setDecimalPoint(scale)
}

fun Number?.moneyConverter(): String {
    val CN_NUMBERS = charArrayOf('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖')
    val CN_UNITS = charArrayOf('分', '角', '元', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿', '拾', '佰', '仟')
    val money = this?.toDouble().orEmpty()
    val sb = StringBuilder()
    var yuan = Math.floor(money).toInt()
    val needYuan = yuan > 0
    if (needYuan) {
        for (i in 0 until yuan.toString().length) {
            sb.append(CN_NUMBERS[yuan % 10])
            sb.append(CN_UNITS[i + 2])
            yuan /= 10
        }
    }
    val jiao = Math.floor(money * 10 % 10).toInt()
    if (jiao > 0) {
        sb.append(CN_NUMBERS[jiao])
        sb.append(CN_UNITS[0])
    }
    val fen = Math.floor(money * 100 % 10).toInt()
    if (fen > 0) {
        sb.append(CN_NUMBERS[fen])
        sb.append(CN_UNITS[1])
    }
    return if (sb.isEmpty()) {
        "零元整"
    } else sb.toString()
}
